import { getYMD, getNowFormatDate, getDay, to5, compareObject, toPercent} from '../../../../assets/js/util.js'

import echarts from 'echarts'

export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: '',
                uid: ''
            },
            popShow: false,
            pickerOptions: {
                shortcuts: [{
                    text: '近1天',
                    onClick(picker) {
                        const end = new Date(new Date().getTime() - 1 * 86400000);
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '近5天',
                    onClick(picker) {
                        const end = new Date(new Date().getTime() - 1 * 86400000);
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 5);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '近10天',
                    onClick(picker) {
                        const end = new Date(new Date().getTime() - 1 * 86400000);
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 10);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            title: '激活转化',
            platForms: [],
            channels: [],
            goToSteps: [],
            loading: false,
            searchable: false,
            ruleForm: {
                date: '',
                platForm: '0',
                channel: '0',
                goToStep: '41',
            },
            tableHead1: [{
                    "prop": "index",
                    "label": "序号"
                },
                {
                    "prop": "stepcode",
                    "label": "步骤号"
                },
                {
                    "prop": "stepcodeName",
                    "label": "步骤名称"
                },
                {
                    "prop": "finishnum",
                    "label": "完成次数"
                },
                {
                    "prop": "uuidnum",
                    "label": "完成设备数"
                },
                {
                    "prop": "distribute",
                    "label": "分步转化率"
                },
                {
                    "prop": "totalAchieve",
                    "label": "累计完成率"
                },
                {
                    "prop": "lostRate",
                    "label": "该步流失率"
                }
            ],
            tableData1All: [],
            tableData1: [],
            tableHead2: [{
                    "prop": "channelId",
                    "label": "渠道ID"
                },
                {
                    "prop": "channelName",
                    "label": "渠道名称"
                },
                {
                    "prop": "beginnum",
                    "label": "点击icon设备数量"
                },
                {
                    "prop": "endnum",
                    "label": " 进入游戏设备数量"
                },
                {
                    "prop": "allRadio",
                    "label": "整体通过率"
                }
            ],
            tableData2All: [],
            tableData2: [],
            detailHead: [{
                    "prop": "index",
                    "label": "序号"
                },
                {
                    "prop": "stepcode",
                    "label": "步骤号"
                },
                {
                    "prop": "stepcodeName",
                    "label": "步骤名称"
                },
                {
                    "prop": "finishnum",
                    "label": " 完成次数"
                },
                {
                    "prop": "uuidnum",
                    "label": "完成设备数"
                },
                {
                    "prop": "distribute",
                    "label": "分步转化率"
                }
            ],
            detailDataAll: [],
            detailData: [],
            /*当前页显示数量*/
            pageSize1: 20,
            /*每页显示的数量*/
            pageSizes1: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal1: 0,
            /*分页器*/
            currentPage1: 1,
            /*当前页显示数量*/
            pageSize2: 20,
            /*每页显示的数量*/
            pageSizes2: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal2: 0,
            /*分页器*/
            currentPage2: 1,
            /*当前页显示数量*/
            pageSize3: 20,
            /*每页显示的数量*/
            pageSizes3: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal3: 0,
            /*分页器*/
            currentPage3: 1,
            // 指定图表的配置项和数据
            // 分小时数据 付费金额
            pay: {
                color: ['#2eb398', '#79bde9', '#9d79d8'],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data: []
                },
                grid: {
                    left: '4%',
                    right: '4%',
                    bottom: '10%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'circle',
                }, {
                    name: '2',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'roundRect',
                }, {
                    name: '3',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'triangle',
                }]
            },
            // 实时数据显示
            realLoadShow: false,
        }
    },
    computed: {

    },
    methods: {
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        //初始化
        _init() {
            var arr = ['sbCount', 'channelPass'];
            for (var x = 0; x < arr.length; x++) {
                this[arr[x] + 'Charts'] = echarts.init(document.getElementById(arr[x]));
                this[arr[x] + 'Charts'].setOption(this.pay);
            }
            window.addEventListener('resize', function() {
                var resizeArr = ['sbCountCharts', 'channelPassCharts']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        dateChange(val) {
            /*this.date = val;*/
        },
        /*渠道数据改变*/
        channelChange() {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=updateChannel`, {
                params: { 'ps': `channel=${this.ruleForm.channel}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data['res']) === 0) {
                    this.platForms = [];
                    for (var i in data.platformItmes) {
                        var obj = {};
                        obj.id = data.platformItmes[i];
                        obj.platFormName = i;
                        this.platForms.push(obj);
                    }
                    /*this.echartsData(data);*/
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*平台数据改变*/
        platFormChange() {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=updatePlatform`, {
                params: { 'ps': `platform=${this.ruleForm.platForm}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data['res']) === 0) {
                    this.channels = [];
                    for (var i in data.channelItmes) {
                        var obj = {};
                        obj.id = data.channelItmes[i];
                        obj.channelName = i;
                        this.channels.push(obj);
                    }
                    /*this.echartsData(data);*/
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        goToStepChange() {

        },
        // 变成分数
        pencent() {
            var data1 = this.tableData1All;
            var data2 = this.tableData2All;
            var datas = this.detailDataAll;
            //转换为%比 
            for (var i = 0; i < data1.length; i++) {
                for (var j in data1[i]) {
                    if (j === 'distribute' || j === 'totalAchieve' || j === 'lostRate') {
                        data1[i][j] = toPercent(data1[i][j]);
                    }
                }
            }
            for (var i = 0; i < data2.length; i++) {
                for (var j in data2[i]) {
                    if (j === 'allRadio') {
                        data2[i][j] = toPercent(data2[i][j]);
                    }
                }
            }
            for (var i = 0; i < datas.length; i++) {
                for (var j in datas[i]) {
                    if (j === 'distribute') {
                        datas[i][j] = toPercent(datas[i][j]);
                    }
                }
            }
            this.tableData1All = data1;
            this.tableData2All = data2;
            this.detailDataAll = datas;
        },
        handleSizeChange1(val) {
            this.pageSize1 = val;
            this.tableControl1();
            /*this.getTableData(this.ruleForm)*/
        },
        handleCurrentChange1(val) {
            this.currentPage1 = val;
            this.tableControl1();
            /*this.getTableData(this.ruleForm)*/
        },
        tableControl1() {
            this.tableData1 = this.tableData1All.slice((this.currentPage1 - 1) * this.pageSize1, this.currentPage1 * this.pageSize1)
        },
        handleSizeChange2(val) {
            this.pageSize2 = val;
            this.tableControl2();
            /*this.getTableData(this.ruleForm)*/
        },
        handleCurrentChange2(val) {
            this.currentPage2 = val;
            this.tableControl2();
            /*this.getTableData(this.ruleForm)*/
        },
        tableControl2() {
            this.tableData2 = this.tableData2All.slice((this.currentPage2 - 1) * this.pageSize2, this.currentPage2 * this.pageSize2)
        },
        handleSizeChange3(val) {
            this.pageSize3 = val;
            this.tableControl3();
            /*this.getTableData(this.ruleForm)*/
        },
        handleCurrentChange3(val) {
            this.currentPage3 = val;
            this.tableControl3();
            /*this.getTableData(this.ruleForm)*/
        },
        tableControl3() {
            this.detailData = this.detailDataAll.slice((this.currentPage3 - 1) * this.pageSize3, this.currentPage3 * this.pageSize3)
        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        /*==================获取下拉列表数据========================*/
        getData() {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=initParam`, {
                params: { 'ps': '' }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data['res']) === 0) {
                    /*=====获取平台======*/
                    for (var i in data.platformItmes) {
                        var obj = {};
                        obj.id = data.platformItmes[i];
                        obj.platFormName = i;
                        this.platForms.push(obj);
                    }

                    /*=====获取渠道名称======*/
                    for (var i in data.channelItmes) {
                        var obj = {};
                        obj.id = data.channelItmes[i];
                        obj.channelName = i;
                        this.channels.push(obj);
                    }
                    /*=====获取进入步骤数据======*/
                    for (var i in data.enterItmes) {
                        var obj = {};
                        obj.id = data.enterItmes[i];
                        obj.goToStepName = i;
                        this.goToSteps.push(obj);
                    }
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*====================时间格式化转换函数============================*/
        formatDate(date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        },
        /*==================获取表格数据========================*/
        getTableData(data) {
            this.loads();
            let date1 = this.formatDate(this.ruleForm.date[0]);
            let date2 = this.formatDate(this.ruleForm.date[1]);
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `dstart=${date1}&dend=${date2}&platform=${data.platForm}&channel=${data.channel}&enterId=${data.goToStep}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                console.log(data)
                if (parseInt(data['res']) === 0) {
                    this.tableData1All = data.dataList1;
                    this.dataTotal1 = data.dataList1.length;
                    this.tableData2All = data.dataListChannel;
                    this.dataTotal2 = data.dataListChannel.length;
                    this.pencent();
                    this.tableControl1();
                    this.tableControl2();
                    this.echartsData(data);
                    /*this.echartsData(data);*/
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*===========================查询功能===============================*/
        search(data) {
            this.loads();
            let date1 = this.formatDate(this.ruleForm.date[0]);
            let date2 = this.formatDate(this.ruleForm.date[1]);
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `dstart=${date1}&dend=${date2}&platform=${data.platForm}&channel=${data.channel}&enterId=${data.goToStep}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data.res) === 0) {
                    if (data.length == 0) {
                        this.errorFun('查询结果为空！')
                    } else {
                        this.tableData1All = data.dataList1;
                        this.dataTotal1 = data.dataList1.length;
                        this.tableData2All = data.dataListChannel;
                        this.dataTotal2 = data.dataListChannel.length;
                        this.pencent();
                        this.tableControl1();
                        this.tableControl2();
                        this.echartsData(data);
                    }
                } else {
                    this.errorFun(data.msg)
                }
            })
        },
        /*===================查看详细=======================*/
        watch(index) {
            this.popShow = true;
            this.loads();
            console.log(index)
            let date1 = this.formatDate(this.ruleForm.date[0]);
            let date2 = this.formatDate(this.ruleForm.date[1]);
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `dstart=${date1}&dend=${date2}&platform=${this.ruleForm.platForm}&channel=${this.ruleForm.channel}&enterId=${this.ruleForm.goToStep}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data.res) === 0) {
                    if (data.dataListChannel.length == 0) {
                        this.errorFun('查询结果为空！')
                    } else {
                        this.tableData1All = data.dataList1;
                        this.dataTotal1 = data.dataList1.length;
                        this.tableData2All = data.dataListChannel;
                        this.dataTotal2 = data.dataListChannel.length;
                        this.detailDataAll = data.dataListChannel[index]['steps'];
                        console.log(this.detailDataAll);
                        this.dataTotal3 = this.detailDataAll.length;
                        this.pencent();
                        this.tableControl1();
                        this.tableControl2();
                        this.tableControl3();
                    }
                } else {
                    this.errorFun(data.msg)
                }
            })
        },
        popClose() {
            this.popShow = false;
        },
        judgeUnderfind(d, key) {
            if (d[key] == undefined) {
                var data1 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data1 = d[key]['jsonStr'];
            }
            return data1
        },
        // 改变表数据
        echartsData(d) {
            // 激活设备步骤转化率获取到数据渲染
            /*var data = d['advChart'][0];*/
            var data = this.judgeUnderfind(d, 'chartData1');
            var data2 = this.judgeUnderfind(d, 'chartData2');
            var el = data2['data'][0];
            var els = data2['data'][1];
            var obj = `${data['names']},${data2['names'][0]},${data2['names'][1]}`.split(",");
            this.sbCountCharts.setOption({
                legend: {
                    data: obj,
                },
                xAxis: {
                    data: data['columnkeys']
                },
                yAxis: [{
                        type: 'value',
                        position: 'left',
                        name: '分布转化率&累计完成率',
                        nameRotate: 90,
                        nameLocation: 'middle',
                        fontSize: '18px',
                        nameGap: 80,
                        axisLabel: {
                            show: true,
                            interval: 'auto',
                            formatter: function(value) {
                                var str = Number(value * 100).toFixed(2);
                                str += "%";
                                return str;
                            }
                        }
                    },
                    {
                        type: 'value',
                        position: 'right',
                        name: '设备数量',
                        nameRotate: 90,
                        nameLocation: 'middle',
                        fontSize: '18px',
                        nameGap: 60,
                    }
                ],
                tooltip: [{
                    trigger: 'axis',
                    formatter: function(a) {
                        var temp = '';
                        for (var i = 0, len = a.length; i < len; i++) {
                            if (i === 0) {
                                temp = temp + a[i].seriesName + ':' + a[i].value + '</br>';
                            } else {
                                temp = temp + a[i].seriesName + ':' + Number(a[i].value * 100).toFixed(2) + '%' + '</br>';
                            }

                        }
                        return a[0].name + '</br>' + temp;
                    }
                }],
                series: [{
                        name: data['names'],
                        type: 'bar',
                        data: data['data'][0],
                        yAxisIndex: 1,
                    },
                    {
                        name: data2['names'][0],
                        type: 'line',
                        data: el,
                        label: {
                            normal: {
                                show: false,
                                position: 'top',
                                formatter: function(value) {
                                    var str = Number(value.data * 100).toFixed(2);
                                    str += "%";
                                    return str;
                                }
                            }
                        }
                    },
                    {
                        name: data2['names'][1],
                        type: 'line',
                        data: els,
                        label: {
                            normal: {
                                show: false,
                                position: 'top',
                                formatter: function(value) {
                                    var str = Number(value.data * 100).toFixed(2);
                                    str += "%";
                                    return str;
                                }
                            }
                        }
                    },
                ]
            });
            // 渠道通过率（TOP20）获取到数据渲染
            /*var data = d['topChart'][0];*/
            var data = this.judgeUnderfind(d, 'chartDataChannel');
            this.channelPassCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                yAxis: [{
                    type: 'value',
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: function(value) {
                            var str = Number(value * 100).toFixed(2);
                            str += "%";
                            return str;
                        }
                    }
                }, ],
                tooltip: [{
                    trigger: 'axis',
                    formatter: function(a) {
                        var temp = '';
                        for (var i = 0, len = a.length; i < len; i++) {
                            temp = temp + a[i].seriesName + ':' + Number(a[i].value * 100).toFixed(2) + '%' + '</br>';
                        }
                        return a[0].name + '</br>' + temp;
                    }
                }],
                series: [{
                    name: data['names'],
                    type: 'bar',
                    data: data['data'][0],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    },
                }]
            });
        },
        // 表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.tableData1All.sort(compareObject(column.prop, false));
            } else { //正序
                this.tableData1All.sort(compareObject(column.prop, true));
            }
            this.tableControl1();
        },
        // 表格排序
        sortChange2(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.tableData2All.sort(compareObject(column.prop, false));
            } else { //正序
                this.tableData2All.sort(compareObject(column.prop, true));
            }
            this.tableControl2();
        }, // 表格排序
        sortChange3(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.detailDataAll.sort(compareObject(column.prop, false));
            } else { //正序
                this.detailDataAll.sort(compareObject(column.prop, true));
            }
            this.tableControl3();
        }

    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
        this.getData();
        this.ruleForm.date = [new Date(new Date().getTime() - 1 * 86400000), new Date(new Date().getTime() - 1 * 86400000)];
        this.getTableData(this.ruleForm);
        this._init();
    }
}